const express = require("express");
const router = express.Router();
const pool = require("../db");

const getListSql = (params) => {
    const { userName, account, pageSize, pageNum } = params;
    let sql = `SELECT * FROM user`;
    if (userName && account) {
      sql += ` where USER_name=${userName} and account=${account}`;
    } else if (userName) {
      sql += ` where USER_name=${userName}`;
    } else if (account) {
      sql += ` where account=${account}`;
    }
    if (pageSize && pageNum) {
      sql += ` limit ${(pageNum - 1) * pageSize},${pageSize}`;
    } else {
      sql += ` limit 0,10`;
    }
    return sql; 
  };
  const getTotalSql = (params) => {
    const { userName, account } = params;
    let sql = `SELECT count(*) FROM user`;
    if (userName && account) {
      sql += ` where USER_name=${userName} and account=${account}`;
    } else if (userName) {
      sql += ` where USER_name=${userName}`;
    } else if (account) {
      sql += ` where account=${account}`;
    }
    return sql; 
  };
//写接口要点：把接口当函数去处理：1.收集参数，考虑要什么参数 2.把整理好的参数给sql语句 3.返回接口格式res.status(200).json({ status: ？, message: ？，data:？ })
//困难点  1.node里面这些对象有什么功能，req：前端传过来的数据，res：返回给前端的数据，next：下一个中间件
//req.body 获取post请求的数据   req.query 获取get请求的数据，可以拼接在路径上的  req.params 获取url中的参数  req.headers 获取请求头
// 用户注册接口
router.post("/register", async (req, res) => {
  const { phone, user_name, password, email, account, sex } = req.body; //post
  const processedData = {
    phone: phone === undefined ? null : phone,
    user_name: user_name === undefined ? null : user_name,
    password: password === undefined ? null : password,
    email: email === undefined ? null : email,
    account: account === undefined ? null : account,
    sex: sex === undefined ? null : sex,
  };

  // 简单验证
  if (!password || !account) {
    return res.status(200).json({ status: false, message: "请填写完整信息" });
  }

  if (sex !== 1 && sex !== 0 && sex !== null && sex !== undefined) {
    return res.status(200).json({ status: false, message: "性别填写错误" });
  }

  try {
    // 检查用户名是否已存在
    const [users] = await pool.execute("SELECT * FROM user WHERE account = ?", [
      account,
    ]);
    if (users.length > 0) {
      return res.status(200).json({ status: false, message: "账号已存在" });
    }
    // 插入新用户
    await pool.execute(
      "INSERT INTO user ( phone, user_name, password, email, account, sex) VALUES (?, ?, ?, ?, ?, ?)",
      [
        processedData.phone,
        processedData.user_name,
        processedData.password,
        processedData.email,
        processedData.account,
        processedData.sex,
      ]
    );
    res.status(200).json({ status: true, message: "注册成功" });
  } catch (error) {
    console.error(error);
    res.status(200).json({ status: false, message: "服务器错误" });
  }
});

// 用户登录接口
router.post("/login", async (req, res) => {
  const { account, password } = req.body;

  // 简单验证
  if (!account || !password) {
    return res.status(200).json({ status: false, message: "请填写账号和密码" });
  }

  try {
    // 检查账号是否存在
    const [users] = await pool.execute("SELECT * FROM user WHERE account = ?", [
      account,
    ]);
    if (users.length === 0) {
      return res.status(200).json({ status: false, message: "账号不存在" });
    }

    // 验证密码
    const user = users[0];
    if (user.password !== password) {
      return res.status(200).json({ status: false, message: "密码错误" });
    }

    // 使用JWT生成token
    const jwt = require("jsonwebtoken");
    const { secret } = require("../secret");
    const token = jwt.sign(
      {
        user,
        exp: Math.floor(Date.now() / 1000) + 4 * 24 * 60 * 60, // 4天过期
      },
      secret // 实际项目中应使用环境变量存储密钥
    );

    res.status(200).json({
      status: true,
      message: "登录成功",
      data: {
        token: "Bearer " + token,
        user,
      },
    });
  } catch (error) {
    console.error(error);
    res.status(200).json({ status: false, message: "服务器错误" });
  }
});

// 用户信息查询接口
router.get("/list", async (req, res) => {
  //pageSize 每页显示的条数 pageNum 当前页码 user_id 用户id
  const { userName, account, pageSize = 10, pageNum = 1 } = req.query;
  const sql1 = getListSql({ userName, account, pageSize, pageNum });
  const sql2 = getTotalSql({ userName, account });
  try {
    // 检查用户名是否已存在
    const [users] = await pool.execute(sql1);
    const [total] = await pool.execute(sql2);
    const data = { datalist: users, totalCount: total[0]["count(*)"] };
    res.status(200).json({ status: true, message: "查询成功", data: data });
  } catch (error) {
    res.status(200).json({ status: false, message: "服务器错误" });
  }
});

//修改接口
router.post("/update", async (req, res) => {
  const { user_id, phone, user_name, email, sex } = req.body;

  // 参数验证
  if (!user_id) {
    return res.status(200).json({ status: false, message: "请提供用户ID" });
  }

  try {
    // 检查用户是否存在
    const [users] = await pool.execute("SELECT * FROM user WHERE USER_id = ?", [user_id]);
    if (users.length === 0) {
      return res.status(200).json({ status: false, message: "用户不存在" });
    }

    // 构建更新字段和参数
    const updateFields = [];
    const params = [];


    if (phone !== undefined) {
      updateFields.push("phone = ?");
      params.push(phone);
    }
    if (user_name !== undefined) {
      updateFields.push("user_name = ?");
      params.push(user_name);
    }
    if (email !== undefined) {
      updateFields.push("email = ?");
      params.push(email);
    }
    if (sex !== undefined) {
      updateFields.push("sex = ?");
      params.push(sex);
    }

    if (updateFields.length === 0) {
      return res.status(200).json({ status: false, message: "未提供更新字段" });
    }

    params.push(user_id); // 最后添加WHERE条件参数
    console.log("🚀 ~ file: userRoute.js:194 ~ a:", updateFields)

    // 执行更新
    await pool.execute(
      `UPDATE user SET ${updateFields.join(", ")} WHERE USER_id = ?`,
      params
    );

    res.status(200).json({ 
      status: true, 
      message: "更新成功",
      data: {
        user_id,
        updatedFields: updateFields.map(f => f.split(" = ")[0])
      }
    });
  } catch (error) {
    console.error("更新用户失败:", error);
    res.status(200).json({ status: false, message: "服务器错误" });
  }
});

//删除接口
router.get("/delete", async (req, res) => {
  const { user_id } = req.query;
  console.log("ID号:",user_id);
  // 参数验证
  if (!user_id) {
    return res.status(200).json({ status: false, message: "请提供用户ID" });
  }
  try {
    // 检查用户是否存在
    const [users] = await pool.execute("SELECT * FROM user WHERE USER_id = ?", [user_id]);
    if (users.length === 0) {
      return res.status(200).json({ status: false, message: "用户不存在" });
    }
    // 执行删除操作
    await pool.execute("DELETE FROM user WHERE USER_id = ?", [user_id]);
    res.status(200).json({ 
      status: true, 
      message: "删除成功",
      data: {
        user_id: user_id
      }
    });
    console.log("error");
  } catch (error) {
    console.error(error);
    res.status(200).json({ status: false, message: "服务器错误" });
  }
});

module.exports = router;
